package com.work.demo.idempotent;

import org.apache.logging.log4j.util.Base64Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.UUID;

@Component
public class IdempotenceUtil {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 生成幂等号
     *
     * @return 幂等号
     */
    public String generateId() {
        String uuid = UUID.randomUUID().toString();
        String uId = Base64Util.encode(uuid).toLowerCase();
        redisTemplate.boundValueOps(uId).set("1", 1800);
        return uId;
    }


    /**
     * 从header中获取幂等号
     *
     * @return 幂等号
     */
    public String getHeaderIdempotenceId() {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        return request.getHeader("idempotenceId");
    }

}
